<template>
	<view class="status-list">
		<div class="status-item" v-for="(item, index) in dataArr" :key="index">
		      <div class="status-item--title">
		        <div>{{ item.createTime }}</div>
		        <div class="red" v-if="item.state === 1 || item.state === 2">
		          待付款
		        </div>
		        <div class="grey" v-if="item.state === 0">已取消</div>
		        <div class="yellow" v-if="item.state === 3">待发货</div>
		        <div class="blue" v-if="item.state === 4">待收货</div>
		        <div class="green" v-if="item.state === 5 || item.state === 6">
		          已完成
		        </div>
		      </div>
		      <div
		        class="status-item--shop"
		        v-for="(j, i) in item.orderList"
		        :key="i"
		        @click="gotoDeatil(item)"
		      >
		        <div class="item-img">
		          <image
				  style=" width: 26vw;height: 26vw;border-radius: 3vw;"
		            :src="j.model.img"
		          />
		        </div>
		        <div class="item-title">
		          <div>{{ j.wares.name }}</div>
		          <div>{{ j.model.specificationsValue.replace(/"|{|}/g, "") }}</div>
		        </div>
		        <div class="item-price">
		          <div><span>￥</span> {{ j.price }}</div>
		          <div>x{{ j.count }}</div>
		        </div>
		      </div>
		     <div
		        class="discount-cost"
		        v-if="(item.totalAmount !== item.needPay)"
		      >
		        <div>优惠</div>
		        <div>- ￥{{ (item.totalAmount - item.needPay).toFixed(2) }}</div>
		      </div>
		      <div class="status-item--cost">
		        <span> 共{{ item.orderList.length }}件</span>
		        <span v-if="item.state === 1 || item.state === 2 || item.state === 0"
		          >应付总额</span
		        >
		        <span v-else>已付总额</span>
		        <span>￥{{ item.needPay.toFixed(2) }}</span>
		      </div>
		      <div class="status-item--btn" v-if="item.state === 0">
		        <view
		          type="primary"
		          :class="disMore[index] ? 'gray-blue' : 'blue-ghost'"
		          @click="goPay(item, index)"
		          >再来一单</view
		        >
		      </div>
		      <view class="status-item--btn" v-if="item.state === 1 || item.state === 2">
		        <view
		          type="primary"
		          :class="disMore[index] ? 'gray-blue' : 'blue-ghost'"
		          @click="goPay(item, index)"
		          >再来一单</view
		        >
		        <view type="primary" @click="cancelOrder(item)" class="grey"
		          >取消订单</view
		        >
		        <view
		          type="primary"
		          @click="pay(item, index)"
		          class="red"
		          :loading="isPay[index]"
		          >立即付款</view
		        >
		      </view>
		      <div class="status-item--btn" v-if="item.state === 3">
		        <view
		          type="primary"
		          :class="disMore[index] ? 'gray-blue' : 'blue-ghost'"
		          @click="goPay(item, index)"
		          >再来一单</view
		        >
		        <view type="primary" @click="tips" class="yellow"
		          >提醒发货</view
		        >
		      </div>
		      <div class="status-item--btn" v-if="item.state === 4">
		        <view
		          type="primary"
		          :class="disMore[index] ? 'gray-blue' : 'blue-ghost'"
		          @click="goPay(item, index)"
		          >再来一单</view
		        >
		        <view
		          type="primary"
		          class="blue-ghost"
		          @click="gotoLogistics(item)"
		          >查看物流</view
		        >
		        <view type="primary" class="blue" @click="confirm(item)"
		          >确认收货</view
		        >
		      </div>
		      <div class="status-item--btn" v-if="item.state === 5">
		        <view
		          type="primary"
		          :class="disMore[index] ? 'gray-blue' : 'blue-ghost'"
		          @click="goPay(item, index)"
		          >再来一单</view
		        >
		        <view type="primary" class="green" @click="openEvaluate(item)"
		          >评价</view
		        >
		      </div>
		      <div class="status-item--btn" v-if="item.state === 6">
		        <view
		          :class="disMore[index] ? 'gray-blue' : 'blue-ghost'"
		          @click="goPay(item, index)"
		          >再来一单</view
		        >
		        <view type="primary" class="grey">已评价</view>
		      </div>
		      <van-divider :style="{ margin: '24px 0' }" />
		    </div>
			
			<van-popup @close="onClose" safe-area-inset-bottom :show="showEvaluate" custom-style="max-height:80vh;min-height:50vh;" round  position="bottom">
					  <div
					        style="
					          height: 8vh;
					          display: flex;
					          align-items: center;
					          font-weight: bold;
					          justify-content: space-between;
					        "
					      >
					        <div
					          style="color: #e15a3b; margin-left: 16px; font-size: 4.3vw"
					          @click="showEvaluate = false"
					        >
					          取消
					        </div>
					        <div style="font-size: 4.8vw">评价</div>
					        <div
					          style="color: #5a9bef; margin-right: 16px; font-size: 4.3vw"
					          @click="submitEvalute"
					        >
					          确定
					        </div>
					      </div>
						  <van-field
						    clearable
						    :value="message"
							@input="handleInput"
						    rows="5"
						    autosize
						    type="textarea"
						    maxlength="100"
						    placeholder="写下您对商品的评价吧（不超过100字）"
						    show-word-limit
						  />
					      <div
					        style="
					          font-size: 4vw;
					          color: #888888;
					          padding: 0 16px 0 16px;
					          display: flex;
					          justify-content: space-between;
					        "
					      >
					        <div>{{ evaluateTime }}</div>
					      </div>
					      <van-divider :style="{ color: '#F2F2F2', }" />
					        <div style="font-size: 4vw; font-weight: bold;margin-left: 32rpx;">星级评价</div>
							<view class="rate-div"><u-rate :size="60" :gutter="50" :count="5" v-model="evaluateValue"></u-rate></view>
			</van-popup>
	</view>
</template>

<script>
	import api from '../untils/api.js'
	export default {
		name:"order-list-item",
		 props: {
		    dataArr: {
		      type: Array,
		    },
		  },
		data() {
			return {
				showEvaluate:false,
				evaluateData:null,
				disMore: [],
				evaluateTime:"",
				message:"",
				evaluateValue: 0,
				evaluateData:{}
			};
		},
		methods:{
			gotoLogistics(item){
				uni.navigateTo({
					url:`../logistics/logistics?id=${item.id}&orderNum=${item.orderNum}`
				})
			},
			//发起支付
		async	pay(item,index){
				if(item.payment === 0){
					 await api.SM_ORDER_PAYMENT(JSON.stringify({id:item.id,payment:0}))
				}
				else {
				 var obj={};
				 obj.id=item.id;
				 obj.clientType=2;
				 obj.modelInfo=[];
				 var modelObj={};
				 item.orderList.forEach((item)=>{
					 modelObj.id=item.model.id
					 modelObj.count=item.count
					 obj.modelInfo.push(modelObj)
				 });
				api.WX_CREATE_SM_PAY(JSON.stringify(obj)).then((res)=>{
									   wx.requestPayment({
									     timeStamp: res.data.body.timeStamp,
									     nonceStr: res.data.body.nonceStr,
									     package: res.data.body.packageValue,
									     signType: 'MD5',
									     paySign: res.data.body.paySign,
									     success: (res)=>{ 
											 uni.redirectTo({
											   url: `../orderDetail/orderDetail?id=${item.id}`
											 })
										 },
									     fail: async (res)=> { 
											 await api.SM_PAY_CANCEL(JSON.stringify(item.id));
											 uni.redirectTo({
											   url: `../orderDetail/orderDetail?id=${item.id}`
											 })
											},
										 // cancel: async (res)=> { 
											//   console.log("dagfsdg")
											//  await api.SM_PAY_CANCEL(JSON.stringify(that.orderId));
											//  uni.redirectTo({
											//    url: `../orderDetail/orderDetail?id=${that.orderId}`
											//  })
											// },
									   })
				})	
				}
			},
			handleInput(e){
				this.message=e.detail
			},
			// 提交评论
			    async submitEvalute() {
			      if (this.message === "") {
			       uni.showToast({
			       	title: "请填写评论！",
			       	icon:'none',
			       	duration:1000
			       });
			        return;
			      }
			      if (this.evaluateValue === 0) {
					  uni.showToast({
					  	title: "请选择评分星级！",
					  	icon:'none',
					  	duration:1000
					  });
			        return;
			      }
			      try {
			        let evaluateList = [];
			        await this.evaluateData.orderList.map((item) => {
			          evaluateList.push({
			            smOrder: { id: this.evaluateData.id },
			            wares: { id: item.wares.id },
			            content: this.message,
			            logisticsScore: this.evaluateValue,
			            waresScore: this.evaluateValue,
			            salerScore: this.evaluateValue,
			            model: { id: item.model.id },
			          });
			        });
			        await api.SM_EVALUATE_LIST_SAVE( JSON.stringify(evaluateList) );
			      } finally {
			        this.$emit("refresh");
			        this.message = "";
			        this.evaluateValue = 0;
			        this.showEvaluate = false;
					uni.showToast({
						title: "评价成功！",
						icon:'none',
						duration:1000
					});
			      }
			    },
			onClose(){
				this.showEvaluate=false
			},
			openEvaluate(item){
				this.showEvaluate=true
				this.evaluateData = item;
				this.evaluateTime=this.$u.timeFormat(new Date().getTime(), 'yyyy-mm-dd hh:MM:ss');
			},
			// 确认收货
		    confirm(item) {
				  var that=this
			      uni.showModal({
					  content: '是否确认收货？',
					  success (res){
					      if (res.confirm) {
							  console.log('用户点击确认')
					        api.SM_ORDER_CONFIRM(JSON.stringify({id:item.id})).then((res)=>{
								if(res.data.header.result_code==0){
									that.$emit("refresh",)
								}
							})
					      } else if (res.cancel) {
					        console.log('用户点击取消')
					      }
					    }
			        })
			 },
			 cancelOrder(item) {
			      this.$emit("goCancelOrder",item)
			 },
			 tips() {
				 uni.showToast({
				 	title: "提醒发货成功，请耐心等待！",
				 	icon:'none',
				 	duration:1000
				 });
			  },
			 // 再来一单
			    async goPay(item, index) {
			      await api.SM_ORDER_SELECT_BY_PRIMARYKEY(JSON.stringify(item.id)).then((res) => {
			        res.data.body.orderList.map((item) => {
			          if (item.wares.state !== 1) {
			            this.disMore[index] = true;
						uni.showToast({
							title: "该订单中有商品已下架，无法生成订单！",
							icon:'none',
							duration:3000
						});
						throw new Error();
			          }
					  if (!item.model.stock||item.count>item.model.stock) {
					    this.disMore[index] = true;
					  	uni.showToast({
					  							title: "该订单中有商品库存不足，无法生成订单！",
					  							icon:'none',
					  							duration:3000
					  						});
					  	throw new Error();
					  }
					  if (item.model.buyLimit!==0&&item.count>item.model.buyLimit) {
					    this.disMore[index] = true;
					  	uni.showToast({
					  							title: "该订单中有商品购买数量超标，无法生成订单！",
					  							icon:'none',
					  							duration:3000
					  						});
					  	throw new Error();
					  }
			        });
			      });
				  var list=[]
				  item.orderList.forEach((item)=>{
					  var obj={};
					  console.log(item)
					  obj.price=item.price;
					  obj.img=item.img;
					  obj.stock=item.stock;
					  obj.id=item.id;
					  obj.specificationsValue=item.specificationsValue;
					  obj.wares=item.wares;
					  obj.model=item.model;
					  obj.count=item.count;
					  list.push(obj)
				  })
				  this.$emit("goConfirmOrder",{ list:list, orderFrom: 2 })
			    },
			gotoDeatil(i){
				this.$emit("goDetail",i.id)
			},
		}
	}
</script>

<style lang='scss' scoped>
	.rate-div{
		width: 100vw;
		display: flex;
		flex-direction: row;
		justify-content: center;
		margin-top: 50rpx;
	}
  .status-list {
     width: 100%;
     background: #fff;
     border-radius: 3vw 3vw 0 0;
     padding: 5vw;
     .status-item {
       .discount-cost {
         margin-top: 3vw;
         font-size: 4vw;
         color: #333;
         font-weight: bold;
         display: flex;
         justify-content: space-between;
         div:last-child {
           color: #cc363c;
         }
       }
       .status-item--title {
         display: flex;
         justify-content: space-between;
         align-items: center;
         font-weight: bold;
         font-size: 4vw;
         & > div:first-child {
           color: #212121;
         }
         .red {
           color: #e0593b;
         }
         .yellow {
           color: #e0ac3a;
         }
         .blue {
           color: #3b89ed;
         }
         .green {
           color: #3fad43;
         }
         .grey {
           color: grey;
         }
       }
       .status-item--shop {
         display: flex;
         margin-top: 5vw;
         .item-img {
           width: 30vw;
           height: 30vw;
         }
         .item-title {
           padding: 3vw 0 0 0;
           width: 42vw;
           & > div:first-child {
             color: #333;
             font-size: 4vw;
             font-weight: bold;
           }
           & > div:last-child {
             color: #999;
             font-size: 3.8vw;
             margin-top: 1vw;
           }
         }
         .item-price {
           padding-top: 3vw;
           width: 23vw;
           text-align: right;
           & > div:first-child {
             font-size: 4.2vw;
             color: #333;
             font-weight: bold;
             span {
               color: #999;
               font-size: 3vw;
             }
           }
           & > div:last-child {
             font-size: 4vw;
             color: #878787;
             margin-top: 1vw;
           }
         }
       }
       .status-item--cost {
         font-size: 3.7vw;
         color: #333333;
         font-weight: bold;
         display: flex;
         justify-content: flex-end;
         margin-top: 4vw;
         span {
           margin-left: 5vw;
         }
         span:last-child red {
           color: #cb353b;
         }
       }
       .status-item--btn {
         margin-top: 6vw;
         display: flex;
         justify-content: flex-end;
         view {
           margin-left: 3vw;
		   line-height: 29px;
		   text-align: center;
         }
         .grey {
           color: #bec4cc;
           background: #fff;
           border: 1px solid #bec4cc;
           border-radius: 1.8vw;
           width: 86px;
           height: 29px;
           font-size: 13px;
         }
         .red {
           color: #fff;
           background: #cb353b;
           border: none;
           border-radius: 1.8vw;
           width: 86px;
           height: 29px;
           font-size: 13px;
         }
         .yellow {
           color: #fff;
           background: #e1ac3b;
           border: none;
           border-radius: 1.8vw;
           width: 86px;
           height: 29px;
           font-size: 13px;
         }
         .blue {
           color: #fff;
           background: #3b8aed;
           border: none;
           border-radius: 1.8vw;
           width: 86px;
           height: 29px;
           font-size: 13px;
         }
         .green {
           color: #fff;
           background: #3fae43;
           border: none;
           border-radius: 1.8vw;
           width: 86px;
           height: 29px;
           font-size: 13px;
         }
         .blue-ghost {
           color: #3b8aed;
           background: #fff;
           border: 1px solid #3b8aed;
           border-radius: 1.8vw;
           width: 86px;
           height: 29px;
           font-size: 13px;
         }
         .gray-blue {
           background: #fff;
           border-radius: 1.8vw;
           width: 86px;
           height: 29px;
           font-size: 13px;
           border: 1px solid #b9cfeb;
           color: #b9cfeb;
         }
       }
     }
     .bottom-text {
       text-align: center;
     }
   }
</style>
